import { useEffect, useRef, useState } from 'react';

// 音量检测
const VolumeMeter = () => {
    const [volume, setVolume] = useState(0);
    const audioRef = useRef<HTMLAudioElement>(null);
    // AudioContext API Doc：https://developer.mozilla.org/zh-CN/docs/Web/API/AudioContext

    const openCamera = async () => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: true,
                video: false,
            });
            const audioElm = audioRef.current as HTMLAudioElement;
            audioElm.srcObject = stream;

            const audioContext = new AudioContext();
        } catch(e) {
            console.log('openCamera error: ', e);
        }
    }

    useEffect(() => {
        openCamera();
    }, []);

    return (
        <div>
            <audio ref={audioRef} controls autoPlay></audio>

            <div
                style={{
                    height: 10,
                    width: volume,
                    borderRadius: '50%',
                    backgroundColor: 'skyblue',
                }}
            />
        </div>
    );
};

export default VolumeMeter;
